import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/service/connect_service.dart';
import 'package:sports_new/controller/service/push_service.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/controller/service/third_login_service.dart';
import 'package:sports_new/controller/service/umeng_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/http/event_dio.dart';
import 'package:sports_new/server/http/request_header.dart';
import 'package:sports_new/utils/attach_detector.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/online_contact.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/h5_page.dart';
import 'package:sports_new/view/navigation_page.dart';
import 'package:sports_new/view/no_privacy/zixun_page.dart';
import 'package:sports_new/view/overlay/live_float_widget.dart';
import 'package:sports_new/widgets/privacy_view.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../widgets/base/qkd_text.dart';
import '../widgets/base/qkd_dialog.dart';

class LaunchPage extends StatefulWidget {
  const LaunchPage({super.key});

  @override
  State<LaunchPage> createState() => _LaunchPageState();
}

class _LaunchPageState extends State<LaunchPage> {
  final umService = Get.find<UmengService>();
  final pushService = Get.find<PushService>();
  final thirdService = Get.find<ThirdLoginService>();
  final resource = Get.find<ResourceService>();
  final MethodChannel initChannel = const MethodChannel("mainInit");
  // final bdService = Get.find<BaiduService>();
  StreamSubscription? pushSub;
  Timer? _timer;
  int? currentTime;
  ResourceEntity? launchData;
  bool hasPushData = false;

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      if (SpUtils.agreePrivacy != true) {
        bool result =
            await Get.dialog(const PrivacyView(), barrierDismissible: false);
        if (result == false) {
          result =
              await Get.dialog(const PrivacyView1(), barrierDismissible: false);
          if (result == false) {
            Get.off(const ZixunPage());
            return;
          }
        }
        if (result) {
          SpUtils.sp.setBool(Constant.agreePrivacy, result);
          Get.back();
        }
      }
      await Future.delayed(const Duration(milliseconds: 200));
      Get.put(LiveFloatController(),permanent: true);
      if(SpUtils.agreePrivacy == true) {
        await AttachDetector.checkSimulator();
        await RequestHeader.init();
        if(Get.find<ConnectService>().hasNetwork) {
          await ModeConfig.init();
          await Get.find<ResourceService>().getResource();
          OnlineContact().init();
          umService.initUm();
          Utils.onEvent('app_enter');
          try {
            await initChannel.invokeMethod("initAds");
          }catch(e){
            Logger().d(e);
          }
          // bdService.initBd();
          // thirdService.initThird();
          pushSub = pushService.dataStream.listen((event) {
            hasPushData = true;
            onTapPush(event);
          });
          await pushService.initPush();
          await resource.getAppStartConfig();
        }
        launchData = resource.appLaunchPage;
        // int delay = 500;
         if (launchData != null) {
          int? second = int.tryParse(launchData!.content!);
          currentTime = second ?? 2;
          update();
          _startCount();
          // delay = (second * 1000).toInt();
        } else {
          Future.delayed(const Duration(milliseconds: 500)).then((value) {
            doJump();
          });
        }
      }
    });
  }

  checkNetwork() async {
    List<ConnectivityResult> result = await Connectivity().checkConnectivity();
    if (result.contains(ConnectivityResult.none)) {
      await Get.dialog(const QkdDialog.single('检测到设备当前未联网，请检查您的网络'),
          barrierDismissible: false);
      await checkNetwork();
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    pushSub?.cancel();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    super.dispose();
  }

  void _startCount() {
    // currentTime = 60;
    // _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (currentTime == 0) {
        doJump();
      } else {
        currentTime = currentTime! - 1;
      }
      update();
    });
  }

  doJump({bool tapImage = false}) {
    // Get.offNamed(Routes.navigation);
    if ((launchData == null ||
            launchData?.href == null ||
            launchData!.href!.length == 0) &&
        tapImage) {
      return;
    }
    _timer?.cancel();
    if (resource.starth5 == null) {
      Utils.onEvent('app_open_poster');
      toHomePage(tapImage ? launchData : null);
    } else {
      if (resource.starth5?.content.hasValue == true) {
        Map<String, dynamic> json = jsonDecode(resource.starth5?.content ?? '');
        if (json['inApp'] == 1) {
          Get.off(H5Page(resource.starth5?.href ?? ''));
        } else {
          launchUrlString(resource.starth5?.href ?? '',
            mode: LaunchMode.externalApplication,
            webViewConfiguration: WebViewConfiguration(
              enableDomStorage: false,
              headers: {'Authorization': User.auth?.token ?? ''}
            )
          );
          // Get.off(() => NavigationPage(),
          //     routeName: Routes.navigation,
          //     transition: Transition.noTransition,
          //     arguments: tapImage ? launchData : null);
          toHomePage(tapImage ? launchData : null);
        }
      }
    }
  }

  toHomePage(dynamic arguments) {
    log("------------------------------------------------------------------------------------------${Get.arguments}");
    Get.off(() => const NavigationPage(),
        routeName: Routes.navigation,
        transition: Transition.noTransition,
        arguments: arguments);
    log("------------------------------------------------------------------------------------------${Get.arguments}");
  }

  onTapPush(Map<String, dynamic> data) {
    _timer?.cancel();
    toHomePage(data);
    // if (SpUtils.loginAuth != null) {
    //   User.fetchUserInfos();
    //   User.fetchConfig();
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          color: Colours.white,
          child: Column(
            children: [
              Expanded(
                child: (launchData == null || hasPushData)
                  ? Image.asset(
                    Utils.getImgPath('launch_middle.png'),
                    width: double.infinity,
                    fit: BoxFit.cover,
                  )
                  : GestureDetector(
                    onTap: () => doJump(tapImage: true),
                    child: CachedNetworkImage(
                      imageUrl: launchData!.imgUrl!,
                      fit: BoxFit.cover,
                      width: double.infinity,
                      placeholder: (context, url) => Container(),
                    ),
                  )
              ),
              Image.asset(
                Utils.getImgPath('launch_bottom.png'),
                height: 120,
                width: double.infinity,
                fit: BoxFit.cover,
              )
            ],
          ),
        ),
        Visibility(
            visible: currentTime != null && !hasPushData,
            child: Positioned(top: 30, right: 20, child: count()))
      ],
    );
  }

  Widget count() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        doJump();
      },
      child: SafeArea(
        child: Container(
          decoration: const BoxDecoration(
              color: Colours.black60,
              borderRadius: BorderRadius.all(Radius.circular(14))),
          width: 70,
          height: 28,
          child: DefaultTextStyle(
            style: const TextStyle(color: Colours.white, fontSize: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  width: 8,
                  child: QkdText('$currentTime'),
                ),
                QkdText('s'),
                const SizedBox(width: 4),
                QkdText('|'),
                const SizedBox(width: 4),
                QkdText('跳过')
              ]
            ),
          ),
        ),
      ),
    );
  }
}
